/**
 * 布局管理器 - 实现自动排版功能
 */
export class LayoutManager {
  constructor(graphManager) {
    this.graphManager = graphManager
    this.graph = graphManager.graph
  }

  /**
   * 水平布局
   */
  horizontalLayout(options = {}) {
    const {
      startX = 50,
      startY = 50,
      nodeWidth = 120,
      nodeHeight = 60,
      nodeSpacing = 150,
      levelSpacing = 200
    } = options

    const nodes = this.graph.getNodes()
    if (nodes.length === 0) return

    // 按层级分组节点
    const levels = this.groupNodesByLevel(nodes)
    
    levels.forEach((levelNodes, levelIndex) => {
      const levelY = startY + levelIndex * levelSpacing
      
      levelNodes.forEach((node, nodeIndex) => {
        const nodeX = startX + nodeIndex * (nodeWidth + nodeSpacing)
        node.position(nodeX, levelY)
      })
    })

    this.graph.centerContent()
  }

  /**
   * 垂直布局
   */
  verticalLayout(options = {}) {
    const {
      startX = 50,
      startY = 50,
      nodeWidth = 120,
      nodeHeight = 60,
      nodeSpacing = 100,
      levelSpacing = 250
    } = options

    const nodes = this.graph.getNodes()
    if (nodes.length === 0) return

    // 按层级分组节点
    const levels = this.groupNodesByLevel(nodes)
    
    levels.forEach((levelNodes, levelIndex) => {
      const levelX = startX + levelIndex * levelSpacing
      
      levelNodes.forEach((node, nodeIndex) => {
        const nodeY = startY + nodeIndex * (nodeHeight + nodeSpacing)
        node.position(levelX, nodeY)
      })
    })

    this.graph.centerContent()
  }

  /**
   * 树形布局
   */
  treeLayout(options = {}) {
    const {
      startX = 400,
      startY = 50,
      nodeSpacing = 150,
      levelSpacing = 200
    } = options

    const nodes = this.graph.getNodes()
    if (nodes.length === 0) return

    // 找到根节点（没有入边的节点）
    const rootNodes = this.findRootNodes(nodes)
    
    rootNodes.forEach((rootNode, rootIndex) => {
      const rootX = startX + rootIndex * 300
      this.layoutSubtree(rootNode, rootX, startY, nodeSpacing, levelSpacing)
    })

    this.graph.centerContent()
  }

  /**
   * 圆形布局
   */
  circularLayout(options = {}) {
    const {
      centerX = 400,
      centerY = 300,
      radius = 200
    } = options

    const nodes = this.graph.getNodes()
    if (nodes.length === 0) return

    const angleStep = (2 * Math.PI) / nodes.length
    
    nodes.forEach((node, index) => {
      const angle = index * angleStep
      const x = centerX + radius * Math.cos(angle)
      const y = centerY + radius * Math.sin(angle)
      node.position(x, y)
    })

    this.graph.centerContent()
  }

  /**
   * 网格布局
   */
  gridLayout(options = {}) {
    const {
      startX = 50,
      startY = 50,
      nodeWidth = 120,
      nodeHeight = 60,
      cols = 4,
      nodeSpacing = 50
    } = options

    const nodes = this.graph.getNodes()
    if (nodes.length === 0) return

    nodes.forEach((node, index) => {
      const row = Math.floor(index / cols)
      const col = index % cols
      const x = startX + col * (nodeWidth + nodeSpacing)
      const y = startY + row * (nodeHeight + nodeSpacing)
      node.position(x, y)
    })

    this.graph.centerContent()
  }

  /**
   * 按层级分组节点
   */
  groupNodesByLevel(nodes) {
    const levels = []
    const visited = new Set()
    const edges = this.graph.getEdges()

    // 找到所有根节点（没有入边的节点）
    const rootNodes = this.findRootNodes(nodes)
    
    rootNodes.forEach(rootNode => {
      this.traverseByLevel(rootNode, 0, levels, visited, edges)
    })

    // 处理孤立的节点
    nodes.forEach(node => {
      if (!visited.has(node.id)) {
        if (!levels[0]) levels[0] = []
        levels[0].push(node)
      }
    })

    return levels
  }

  /**
   * 按层级遍历节点
   */
  traverseByLevel(node, level, levels, visited, edges) {
    if (visited.has(node.id)) return
    
    visited.add(node.id)
    
    if (!levels[level]) levels[level] = []
    levels[level].push(node)

    // 找到所有出边
    const outEdges = edges.filter(edge => edge.getSourceCell() === node)
    
    outEdges.forEach(edge => {
      const targetNode = edge.getTargetCell()
      if (targetNode && !visited.has(targetNode.id)) {
        this.traverseByLevel(targetNode, level + 1, levels, visited, edges)
      }
    })
  }

  /**
   * 找到根节点
   */
  findRootNodes(nodes) {
    const edges = this.graph.getEdges()
    const hasIncoming = new Set()

    edges.forEach(edge => {
      const targetNode = edge.getTargetCell()
      if (targetNode) {
        hasIncoming.add(targetNode.id)
      }
    })

    return nodes.filter(node => !hasIncoming.has(node.id))
  }

  /**
   * 布局子树
   */
  layoutSubtree(node, x, y, nodeSpacing, levelSpacing) {
    node.position(x, y)

    const edges = this.graph.getEdges()
    const children = edges
      .filter(edge => edge.getSourceCell() === node)
      .map(edge => edge.getTargetCell())
      .filter(child => child)

    if (children.length === 0) return

    const totalWidth = (children.length - 1) * nodeSpacing
    const startX = x - totalWidth / 2

    children.forEach((child, index) => {
      const childX = startX + index * nodeSpacing
      const childY = y + levelSpacing
      this.layoutSubtree(child, childX, childY, nodeSpacing, levelSpacing)
    })
  }

  /**
   * 自动选择最佳布局
   */
  autoLayout() {
    const nodes = this.graph.getNodes()
    const edges = this.graph.getEdges()

    if (nodes.length === 0) return

    // 根据节点数量和连接关系选择布局
    if (edges.length === 0) {
      // 没有连线，使用网格布局
      this.gridLayout()
    } else if (this.isTreeStructure(nodes, edges)) {
      // 树形结构，使用树形布局
      this.treeLayout()
    } else if (nodes.length <= 8) {
      // 节点较少，使用圆形布局
      this.circularLayout()
    } else {
      // 其他情况，使用水平布局
      this.horizontalLayout()
    }
  }

  /**
   * 判断是否为树形结构
   */
  isTreeStructure(nodes, edges) {
    if (edges.length !== nodes.length - 1) return false

    const visited = new Set()
    const adjacencyList = new Map()

    // 构建邻接表
    nodes.forEach(node => {
      adjacencyList.set(node.id, [])
    })

    edges.forEach(edge => {
      const source = edge.getSourceCell()
      const target = edge.getTargetCell()
      if (source && target) {
        adjacencyList.get(source.id).push(target.id)
        adjacencyList.get(target.id).push(source.id)
      }
    })

    // 检查连通性
    const rootNodes = this.findRootNodes(nodes)
    if (rootNodes.length === 0) return false

    this.dfs(rootNodes[0].id, adjacencyList, visited)
    return visited.size === nodes.length
  }

  /**
   * 深度优先搜索
   */
  dfs(nodeId, adjacencyList, visited) {
    if (visited.has(nodeId)) return
    
    visited.add(nodeId)
    const neighbors = adjacencyList.get(nodeId) || []
    
    neighbors.forEach(neighborId => {
      this.dfs(neighborId, adjacencyList, visited)
    })
  }

  /**
   * 清理布局
   */
  dispose() {
    // 清理资源
  }
} 